package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"path/filepath"
	"strings"
	"time"

	"gateway/websocket"
)

// StaticFileHandler 自定义静态文件处理器，确保正确的MIME类型
type StaticFileHandler struct {
	http.Dir
}

func (h *StaticFileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 获取文件路径
	path := r.URL.Path
	if path == "" {
		path = "/"
	}
	
	// 打开文件
	file, err := h.Open(path)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	defer file.Close()
	
	// 获取文件信息
	stat, err := file.Stat()
	if err != nil {
		http.NotFound(w, r)
		return
	}
	
	// 设置正确的MIME类型
	ext := strings.ToLower(filepath.Ext(path))
	switch ext {
	case ".js":
		w.Header().Set("Content-Type", "application/javascript")
	case ".css":
		w.Header().Set("Content-Type", "text/css")
	case ".html":
		w.Header().Set("Content-Type", "text/html")
	case ".json":
		w.Header().Set("Content-Type", "application/json")
	case ".png":
		w.Header().Set("Content-Type", "image/png")
	case ".jpg", ".jpeg":
		w.Header().Set("Content-Type", "image/jpeg")
	case ".gif":
		w.Header().Set("Content-Type", "image/gif")
	case ".svg":
		w.Header().Set("Content-Type", "image/svg+xml")
	default:
		w.Header().Set("Content-Type", "application/octet-stream")
	}
	
	// 设置缓存头
	w.Header().Set("Cache-Control", "public, max-age=3600")
	
	// 服务文件
	http.ServeContent(w, r, path, stat.ModTime(), file)
}

// 修复路由冲突的WebSocket服务器
func main() {
	fmt.Println("启动WebSocket实时听单服务器...")

	// 创建Hub
	hub := websocket.NewHub()
	go hub.Run()

	// 设置WebSocket路由
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		websocket.ServeWS(hub, w, r)
	})

	// 设置templates目录的静态文件服务
	http.Handle("/templates/", http.StripPrefix("/templates/", http.FileServer(http.Dir("./templates/"))))
	
	// 设置static目录的静态文件服务，确保正确的MIME类型
	http.Handle("/static/", http.StripPrefix("/static/", &StaticFileHandler{http.Dir("./static/")}))

	// 测试页面路由
	http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "./templates/test_websocket.html")
	})
	
	// 整合的前端页面路由
	http.HandleFunc("/demo", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "./templates/websocket_demo.html")
	})
	
	// 状态机流程图页面
	http.HandleFunc("/state-machine", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "./templates/state_machine.html")
	})
	
	// 实时听单页面路由
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/" {
			http.ServeFile(w, r, "./templates/index.html")
		} else {
			// 处理其他静态文件
			http.FileServer(http.Dir("./")).ServeHTTP(w, r)
		}
	})
	
	// 接单逻辑处理操作界面路由
	http.HandleFunc("/acceptance", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "./templates/order_acceptance.html")
	})
	
	// API测试页面路由
	http.HandleFunc("/test-api", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "./templates/test_api.html")
	})
	
	// WebSocket测试页面路由
	http.HandleFunc("/ws-test", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "./templates/websocket_test.html")
	})

	// 启动模拟数据推送
	go simulateOrderUpdates(hub)

	fmt.Println("服务器启动在端口 :8080")
	fmt.Println("访问 http://localhost:8080 查看实时听单界面")
	fmt.Println("访问 http://localhost:8080/acceptance 查看接单逻辑处理操作界面")
	fmt.Println("访问 http://localhost:8080/state-machine 查看订单状态机流程图")
	fmt.Println("访问 http://localhost:8080/test-api 测试API接口")
	fmt.Println("访问 http://localhost:8080/ws-test 测试WebSocket连接")
	fmt.Println("访问 http://localhost:8080/demo 查看整合的前端页面")
	fmt.Println("访问 http://localhost:8080/test 进行WebSocket测试")
	fmt.Println("静态文件位置: ./templates/")

	log.Fatal(http.ListenAndServe(":8080", nil))
}

// 模拟订单更新
func simulateOrderUpdates(hub *websocket.Hub) {
	ticker := time.NewTicker(10 * time.Second)
	defer ticker.Stop()

	orderCounter := 1

	for {
		select {
		case <-ticker.C:
			// 模拟订单创建
			orderData := map[string]interface{}{
				"order_id":       orderCounter,
				"order_no":       fmt.Sprintf("ORD%06d", orderCounter),
				"order_status":   1,
				"payment_status": 1,
				"total_amount":   1000 + orderCounter*100,
				"paid_amount":    0,
				"tenant_id":      fmt.Sprintf("tenant_%03d", orderCounter%10),
				"landlord_id":    fmt.Sprintf("landlord_%03d", orderCounter%5),
				"created_at":     time.Now().Format(time.RFC3339),
				"updated_at":     time.Now().Format(time.RFC3339),
			}

			message := websocket.Message{
				Type:    "order_created",
				Data:    orderData,
				OrderID: uint64(orderCounter),
			}

			messageData, err := json.Marshal(message)
			if err != nil {
				fmt.Printf("序列化消息失败: %v\n", err)
				continue
			}

			// 广播给所有连接的客户端
			hub.BroadcastToAll(messageData)

			fmt.Printf("模拟订单创建: ORD%06d\n", orderCounter)
			orderCounter++

			// 模拟状态变更
			if orderCounter%3 == 0 {
				time.Sleep(2 * time.Second)

				statusChange := map[string]interface{}{
					"order_id":   orderCounter - 1,
					"order_no":   fmt.Sprintf("ORD%06d", orderCounter-1),
					"old_status": 1,
					"new_status": 2,
					"updated_at": time.Now().Format(time.RFC3339),
				}

				statusMessage := websocket.Message{
					Type:    "order_status_change",
					Data:    statusChange,
					OrderID: uint64(orderCounter - 1),
				}

				statusData, err := json.Marshal(statusMessage)
				if err == nil {
					hub.BroadcastToAll(statusData)
					fmt.Printf("模拟状态变更: ORD%06d\n", orderCounter-1)
				}
			}
		}
	}
}
